package com.zjh.springsecuritysplitverifycode.config;

import com.zjh.springsecuritysplitverifycode.filter.VerifyFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails userDetails = User.builder().username("root").password("{noop}123").roles("ADMIN").build();


        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(userDetails);
        return inMemoryUserDetailsManager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public VerifyFilter verifyFilter() throws Exception {
        VerifyFilter verifyFilter = new VerifyFilter();
        verifyFilter.setFilterProcessesUrl("/doLogin");
        verifyFilter.setUsernameParameter("username");
        verifyFilter.setPasswordParameter("password");
        verifyFilter.setAuthenticationManager(authenticationManagerBean());

        verifyFilter.setAuthenticationManager(authenticationManagerBean());
        verifyFilter.setAuthenticationSuccessHandler((request, response, authentication) -> {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("登录成功");
        });
        verifyFilter.setAuthenticationFailureHandler((request, response, exception) -> {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("登录失败");
        });
        return verifyFilter;
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/verify").permitAll()
                .mvcMatchers("/login.html").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> {
                    response.setContentType("application/json;charset=utf-8");
                    response.setStatus(401);
                    response.getWriter().write("请认证");
                })
                .and()
                .logout()
                .and()
                .formLogin()
                .and()
                .csrf().disable();

        http.addFilterAt(verifyFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
